
/**
 * API for work with delicious.
 */
function DeliciousAPI(){
    /**
     * Save bookmark to the current page.
     */
    this.saveBookmark = function(){
        // Send request to the current tab when clicked.
        chrome.tabs.getSelected(null, function(tab){
            var port = chrome.tabs.connect(tab.id, {
                name: "deliciousBookmark"
            });
            port.postMessage({
                action: 'getSelection'
            });
        });
    };
    
    /**
     * Add bookmark.
     */
    this.addBookmark = function(id, bookmark){
        // TODO: Implement.
        saveBookmark();
    };
    
    this.openDelicious = function(){
        var userName = localStorage.userName;
        var url = "http://delicious.com/" + (userName || "");
        
        chrome.tabs.create({
            url: url
        });
    };
    
    this.refreshURL = function(url, targetDiv){
        var dataProvider = new DeliciousDataProvider();
        dataProvider.getURL(url, function(info){
        
            // CR: not safe, think about other solution.
            var resp = eval("(" + info.response + ")");
            
            var list = document.createElement("ul");
            targetDiv.appendChild(list);
            for (var bookmark in resp) {
                var bookmarkItem = document.createElement("a");
                bookmarkItem.setAttribute("href", resp[bookmark].u);
                bookmarkItem.setAttribute("target", "_blank");
                bookmarkItem.appendChild(document.createTextNode(resp[bookmark].d));
                
                var listItem = document.createElement("li");
                listItem.appendChild(bookmarkItem);
                list.appendChild(listItem);
            }
        });
    };
    
    this.refreshList = function(targetId){
        var userName = localStorage.userName;
        
        var url = "http://feeds.delicious.com/v2/json/" + (userName || "");
        
        var tags = localStorage.favouriteTags;
        
        var targetDiv = document.getElementById(targetId);
        targetDiv.innerHTML = "";
        
        if (tags && tags !== "") {
            var tagArray = tags.trim().split(",");
            for (var i = 0; i < tagArray.length; i++) {
            
                var tagId = "tag_" + tagArray[i];
                
                var taggedDiv = document.createElement("div");
                taggedDiv.setAttribute("id", tagId);
                taggedDiv.setAttribute("class", "favoriteTag");
                targetDiv.appendChild(taggedDiv);
                
                var taggedUrl = url + "/" + tagArray[i];
                
                taggedDiv.innerHTML = "<h3>" + tagArray[i] + "</h3>";
                
                this.refreshURL(taggedUrl, taggedDiv);
                
            }
        }
        // Process single url, load recent bookmarks.
        else {
            this.refreshURL(url, targetDiv);
        }
    };
    
    this.getShareStatus = function(){
        var markPrivate = localStorage.markPrivate;
        var share = "yes";
        if (markPrivate === "true") {
            share = "no";
        }
        return share;
    };
    
    this.doSave = function(url, title, selection){
        console.log(["Processing bookmark", url, title, selection]);
        
        if (!url || url === "") {
            console.log("Cannot detect url for saving");
            return;
        }
        
        var encURL = encodeURIComponent(url);
        
        var encTitle = encodeURIComponent(title);
        var encDescription = encodeURIComponent(selection);
        var share = this.getShareStatus();
        
        var f = 'http://delicious.com/save?url=' + encURL + '&title=' + encTitle + '&notes=' + encDescription +
        '&share=' +
        share +
        '&v=5&';
        window.open(f + 'noui=1&jump=doclose', 'deliciousuiv5', 'location=yes,links=no,scrollbars=no,toolbar=no,width=550,height=550');
        
    };
    
    this.registerContentChannel = function(){
        chrome.extension.onConnect.addListener(function(port){
            console.assert(port.name == "deliciousBookmark");
            port.onMessage.addListener(function(msg){
                console.log(["Got message from extension: ", msg.action]);
                
                if (msg.action === 'saveBookmark') {
                    chrome.tabs.getSelected(null, function(tab){
                        var url = msg.url;
                        if (!url || url === "") {
                            url = tab.url;
                        }
						var title = msg.title;
                        if (!title || title === "") {
                            title = tab.title;
                        }
                        new DeliciousAPI().doSave(url, title, msg.selection);
                    });
                    
                }
                if (msg.action === 'getShortcutRequest') {
                    var configuredShortcut = (localStorage['shortcut'] || 'ctrl+m');
                    
                    chrome.tabs.getSelected(null, function(tab){
                        var port = chrome.tabs.connect(tab.id, {
                            name: "deliciousBookmark"
                        });
                        port.postMessage({
                            'action': 'getShortcutResponse',
                            'shortcut': configuredShortcut
                        });
                    });
                    
                }
                
            });
        });
    };
    
    this.registerBookmarkListener = function(){
        // Register listener to receive events about new bookmarks.
        if (chrome.bookmarks.getTree) {
            // FIXME: Workaround for bug 28136
            chrome.bookmarks.getTree(function(bookmarks){
                console.log("Registering bookmark listener.");
                chrome.bookmarks.onCreated.addListener(function(id, bookmark){
                    var shouldSync = "true" === "" + localStorage.syncWithChromeBookmarks;
                    console.log(["Should sync", shouldSync]);
                    if (shouldSync) {
                        console.log("Saving new bookmark: " + id);
                        new DeliciousAPI().saveBookmark();
                    }
                });
            });
        }
        
    };
    
    this.init = function(){
        this.registerContentChannel();
        this.registerBookmarkListener();
    };
}
